package com.zjjxy.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zjjxy.constant.JwtClaimsConstant;
import com.zjjxy.mapper.TeacherMapper;
import com.zjjxy.pojo.dto.StudentAnswerDTO;
import com.zjjxy.pojo.entity.Question;
import com.zjjxy.pojo.entity.Student;
import com.zjjxy.pojo.entity.StudentAnswer;
import com.zjjxy.properties.JwtProperties;
import com.zjjxy.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service

public class TeacherServiceImpl implements  TeacherService {
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public void add(Question question) {
        question.setCreateTime(LocalDateTime.now());
        question.setUpdateTime(LocalDateTime.now());

        teacherMapper.insert(question);
    }

    @Override
    public List<StudentAnswer> getScore() {
        return teacherMapper.getScore();
    }

    @Override
    public List<Question> ranDow() {
        return teacherMapper.ranDow();
    }

    @Override
    public void post(StudentAnswerDTO studentAnswerDTO) {
        String token = studentAnswerDTO.getToken();
        Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);

        int studentNo = (int) claims.get(JwtClaimsConstant.NO);
        int questionId = studentAnswerDTO.getQuestionId();

        Student student = teacherMapper.getByStudentNo(studentNo);

        //填充实体类
        StudentAnswer studentAnswer = new StudentAnswer();
        BeanUtils.copyProperties(studentAnswerDTO, studentAnswer);
        studentAnswer.setScore(teacherMapper.getScoreById(questionId));
        studentAnswer.setTime((int) (teacherMapper.getUpdateTime() - System.currentTimeMillis()));
        studentAnswer.setCreateTime(LocalDateTime.now());
        studentAnswer.setUpdateTime(LocalDateTime.now());

        teacherMapper.post(studentAnswer);
    }

    @Override
    public void publish(Integer id) {
        Question question = new Question();
        question.setId(id);
        question.setStatus("start");
        question.setUpdateTime(LocalDateTime.now());
        teacherMapper.update(question);
    }

    /**
     * 停止发布题目
     * @param id
     */
    @Override
    public void stop(Integer id) {
        Question question = new Question();
        //修改status和updateTime
        question.setId(id);
        question.setStatus("stop");
        question.setUpdateTime(LocalDateTime.now());
        teacherMapper.update(question);
        teacherMapper.update(question);
    }

}
